const express = require("express");
// 有什么难的，express, mysql, sequelize, zpqy, sequelize-cli 所有技术都只是我的工具而已，怕什么？
const { Course, User, Category, Chapter } = require("../../models");
const { Op } = require("sequelize");
const { success, fail } = require("../../utils/response");
const { NotFound, BadRequest, Conflict } = require("http-errors");
/**
 * 课程路由-管理后台
 * 1.分页查询 支持keywords查询
 * 2.查询所有，暂不需要
 * 3.课程详情
 * 4.增加课程
 * 5.删除课程
 * 6.修改课程
 */
const router = express.Router();
// 查询课程-带分页
router.get("/", async (req, res) => {
  try {
    const { pageNum, pageSize } = req.query;
    const conditions = getConditions(req);
    const { count, rows } = await Course.findAndCountAll(conditions);
    success(res, "获取成功", {
      pageNum,
      pageSize,
      count,
      list: rows,
    });
  } catch (error) {
    // console.log("自主抛出的错误！", error.name);
    fail(res, error);
  }
});
// 获取参数
function getConditions(req) {
  const { keywords, pageNum, pageSize, CategoryId, UserId, isRecommend } = req.query;
  const conditions = {
    where: {},
  };
  // 分页参数，没传分页 就是查询所有
  const page = Math.abs(pageNum);
  const size = Math.abs(pageSize);
  if (page && size) {
    conditions.offset = (page - 1) * size;
    conditions.limit = size;
  }
  // 处理普通参数
  if (keywords) {
    conditions.where.name = {
      [Op.like]: `%${keywords}%`,
    };
  }
  if (CategoryId) {
    conditions.where.CategoryId = CategoryId;
  }
  if (UserId) {
    conditions.where.UserId = UserId;
  }
  if (isRecommend) {
    conditions.where.isRecommend = isRecommend;
  }
  return conditions;
}
// 查询课程-无分页
router.get("/all", async (req, res) => {
  try {
    const { keywords } = req.query;
    let where = {};

    if (keywords) {
      where.name = {
        [Op.like]: `%${keywords}%`,
      };
    }
    const raws = await Course.findAll({ where });
    success(res, "获取成功", raws);
  } catch (error) {
    fail(res, error);
  }
});
// 查询课程详情
router.get("/:id", async (req, res) => {
  try {
    const { id } = req.params;
    // 怎么包含它的章节？
    // 怎么在详情里拿到所属的用户信息、分类信息
    if (!id) {
      throw BadRequest("课程id不能为空");
    }
    const conditions = {
      attributes: ["id", "name", "isRecommend", "imgUrl", "UserId"],
      include: [
        {
          model: Category,
          as: "category",
          attributes: ["id", "name"],
        },
        {
          model: User,
          as: "user",
          attributes: ["id", "nickname"],
        },
      ],
    };
    const course = await Course.findByPk(id, conditions);
    if (!course) {
      throw NotFound("未找到此课程");
    }
    success(res, "获取成功", course);
  } catch (error) {
    fail(res, error);
  }
});
// 增加课程
router.post("/", async (req, res) => {
  try {
    const param = filterParamByWhiteName(req);
    const course = await Course.create(param);
    console.log("course", course);
    success(res, "success", course);
  } catch (error) {
    fail(res, error);
  }
});
// 修改课程
router.put("/:id", async (req, res) => {
  try {
    const { id } = req.params;
    const param = filterParamByWhiteName(req);
    const course = await Course.update(param, {
      where: {
        id,
      },
    });
    if (!course) {
      throw NotFound("未找到此课程");
    }
    success(res, "success", course);
  } catch (error) {
    fail(res, error);
  }
});
// 删除课程
router.delete("/:id", async (req, res) => {
  try {
    const { id } = req.params;
    const count = await Chapter.count({ where: { CourseId: id } });
    console.log("count==", count);

    if (count > 0) {
      throw new Conflict("该课程有章节，无法删除");
    }
    const course = await Course.destroy({
      where: { id },
    });
    if (!course) {
      throw NotFound("未找到此课程");
    }
    success(res, "success");
  } catch (error) {
    fail(res, error);
  }
});
// 拿到需要的请求参数 - 用于新增、编辑、查询条件
function filterParamByWhiteName(req) {
  const { CategoryId, UserId, name, isRecommend, imgUrl, introduce, content, rank } = req.body;
  return {
    CategoryId,
    UserId,
    name,
    isRecommend,
    imgUrl,
    introduce,
    content,
    rank,
  };
}

module.exports = router;
